<template>
  <div class="app-container">
    <!--查询条件表单-->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="年级" prop="gradeId">
        <el-select v-model="queryParams.gradeId" @change="queryGradeChangeHandle" placeholder="年级" clearable>
          <el-option v-for="item in gradeOptions" :key="item.gradeId" :label="item.gradeName" :value="item.gradeId" />
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="clazzId">
        <el-select v-model="queryParams.clazzId" placeholder="班级" clearable>
          <el-option v-for="item in clazzOptions" :key="item.clazzId" :label="item.clazzName" :value="item.clazzId" />
        </el-select>
      </el-form-item>
      <el-form-item label="课程" prop="courseId">
        <el-select v-model="queryParams.courseId" placeholder="课程" clearable>
          <el-option v-for="item in courseOptions" :key="item.courseId" :label="item.courseName" :value="item.courseId" />
        </el-select>
      </el-form-item>
      <el-form-item label="教师" prop="leaderId">
        <el-select v-model="queryParams.leaderId" placeholder="教师" clearable>
          <el-option v-for="item in teacherOptions" :key="item.teacherId" :label="item.teacherName" :value="item.teacherId" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option v-for="dict in sys_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-col>
        <el-col :span="1.5">
            <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermission="['school:score:import']">成绩批量导入</el-button>
        </el-col>
          <el-col :span="1.5">
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <!--按钮操作区-->
    <!--数据表格区-->
    <el-table v-loading="loading" :data="clazzCourseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="班课ID" align="center" prop="clazzCourseId" />
      <el-table-column label="年级" align="center" prop="gradeName" />
      <el-table-column label="班级" align="center" prop="clazzName" />
      <el-table-column label="课程" align="center" prop="courseName" />
      <el-table-column label="科任老师" align="center" prop="leaderName" />
      <el-table-column label="学生数量" align="center" prop="studentCount" />
      <el-table-column label="考试次数" align="center" prop="examCount" />
      <el-table-column label="成绩记录数" align="center" prop="scoreCount" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="406" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleScoreEnter(scope.row)"
              v-hasPermission="['school:score:add']"
          >成绩录入</el-button
          >
          <el-button
              link
              type="primary"
              icon="Plus"
              @click="handleScoreBatchEnter(scope.row)"
              v-hasPermission="['school:score:batch_add']"
          >批量录入</el-button
          >
          <el-button
              link
              type="primary"
              icon="Histogram"
              @click="handleScoreEchartsView(scope.row)"
              v-hasPermission="['school:score:echarts_list']"
          >图表分析</el-button
          >
          <el-button
              link
              type="primary"
              icon="UploadFilled"
              @click="handleScoreUpload(scope.row)"
              v-hasPermission="['school:score:upload']"
          >上传试卷</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!--表格分页-->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改班级课程对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="scoreRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="年级" prop="gradeName">
              <el-input v-model="form.gradeName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="clazzName">
              <el-input v-model="form.clazzName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程" prop="courseName">
              <el-input v-model="form.courseName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科任老师" prop="leaderName">
              <el-input v-model="form.leaderName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="考试" prop="examId">
              <el-select v-model="form.examId" placeholder="请选择" @change="handleExamChange">
                <el-option
                    v-for="item in examOptions"
                    :key="item.examId"
                    :label="item.examCombinationName"
                    :value="item.examId"
                    :disabled="item.status == 0"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学生" prop="studentId">
              <el-select v-model="form.studentId"   placeholder="请选择" @change="handleStudentChange">
                <el-option
                    v-for="item in studentOptions"
                    :key="item.studentId"
                    :label="item.year + '/' + item.studentName"
                    :value="item.studentId"
                    :disabled="item.status == 0"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分数" prop="examScore">
              <el-input-number v-model="form.examScore" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="薄弱点" prop="knowledgeIds" v-if="knowledgeOptions.length > 0">
              <el-checkbox-group v-model="form.knowledgeIds">
                <el-checkbox :label="item.knowledgeId" :key="item.knowledgeId"  v-for="item in knowledgeOptions" >
                  {{item.knowledgeName}}({{item.score}})
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="评语" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table v-loading="scoreLoading" :data="scoreList">
              <el-table-column label="成绩ID" align="center" prop="scoreId" />
              <el-table-column label="年度" align="center" prop="year" />
              <el-table-column label="学生" align="center" prop="studentName" />
              <el-table-column label="得分" align="center" prop="examScore" />
              <el-table-column label="等级" align="center" prop="examScoreDegreeStr" />
              <el-table-column label="操作" width="206" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleScoreDelete(scope.row)"
                      v-hasPermission="['school:score:delete']"
                  >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!--表格分页-->
            <pagination
                v-show="scoreTotal > 0"
                :total="scoreTotal"
                v-model:page="scoreQueryParams.pageNum"
                v-model:limit="scoreQueryParams.pageSize"
                @pagination="getScoreList"
            />
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

<!--批量导入-->
    <el-dialog :title="batchTitle" v-model="batchOpen" width="600px" append-to-body>
      <el-form ref="batchScoreRef" :model="batchForm" :rules="batchRules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="年级" prop="gradeName">
              <el-input v-model="batchForm.gradeName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="clazzName">
              <el-input v-model="batchForm.clazzName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程" prop="courseName">
              <el-input v-model="batchForm.courseName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科任老师" prop="leaderName">
              <el-input v-model="batchForm.leaderName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="考试" prop="examId">
              <el-select v-model="batchForm.examId" placeholder="请选择"  @change="handleExamBatchChange">
                <el-option
                    v-for="item in examOptions"
                    :key="item.examId"
                    :label="item.examCombinationName"
                    :value="item.examId"
                    :disabled="item.status == 0"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" v-for="item in studentOptions">
            <el-form-item :label="item.studentName"  :prop="'examScore_'+item.studentId" :key="'examScore_'+item.studentId" >
              <el-input-number v-model="batchForm['examScore_'+item.studentId]" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBatchForm">确 定</el-button>
          <el-button @click="cancelBatch">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--图表分析弹出框-->
    <el-dialog :title="echartsTitle" v-model="echartsOpen" width="80%"  append-to-body>
      <el-row>
        <el-col :span="24">
          <div ref="clazzPhysicalScoreLineStats" style="height: 420px" />
        </el-col>
      </el-row>
      <el-divider/>
      <el-row>
        <el-col :span="24">
          <div ref="clazzPhysicalScoreBarStats" style="height: 420px" />
        </el-col>
      </el-row>
      <el-divider/>
      <el-row>
        <el-col :span="12">
          <div ref="clazzPhysicalScorePieStats" style="height: 420px" />
        </el-col>
        <el-col :span="12">
          <div ref="clazzPhysicalScoreRectStats" style="height: 420px" />
        </el-col>
      </el-row>
      <el-divider/>
      <el-row>
        <el-col :span="24">
          <div class="el-table el-table--enable-row-hover el-table--medium el-table--border">
          <table class="el-table__body" cellspacing="0" style="width: 100%" v-if="tableData.length > 0">
            <thead>
            <tr class="el-table__row">
              <template v-for="(item, index) in tableData[0]">
                <td style="text-align: center" class="el-table__cell" v-if="index == 0" rowspan="2"><b>{{item}}</b></td>
                <td style="text-align: center" class="el-table__cell" v-else colspan="2"><b>{{item}}</b></td>
              </template>
            </tr>
            <tr class="el-table__row">
              <template v-for="(item, index) in tableData[1]">
                <td style="text-align: center" class="el-table__cell"><b>{{item}}</b></td>
              </template>
            </tr>
            </thead>
            <tbody>
            <template v-for="(item, index) in tableData">
              <tr class="el-table__row" v-if="index > 1">
                <template v-for="subItem in item">
                  <td style="text-align: center" class="el-table__cell" v-html="subItem"></td>
                </template>
              </tr>
            </template>
            </tbody>
          </table>
          </div>
        </el-col>
      </el-row>
      <el-divider/>
      <el-row>
        <el-col :span="24">
          <div ref="clazzPhysicalScoreWordCloudStats" id="clazzPhysicalScoreStats" style="height: 500px" />
        </el-col>
      </el-row>
      <el-divider/>
      <el-row>
        <el-col :span="24">
          <div ref="clazzPhysicalScoreStackLineStats" style="height: 420px" />
        </el-col>
      </el-row>
      <el-divider/>
      <el-row>
        <el-col :span="24">
          <div ref="clazzPhysicalScoreStackBarStats" style="height: 420px" />
        </el-col>
      </el-row>
    </el-dialog>

   <!-- 上传试卷图片对话框 -->
    <el-dialog :title="uploadTitle" v-model="uploadOpen" width="800px"  append-to-body>
      <el-form ref="uploadExamPaperRef" :model="uploadForm" :rules="uploadRules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="年级" prop="gradeName">
              <el-input v-model="uploadForm.gradeName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="clazzName">
              <el-input v-model="uploadForm.clazzName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程" prop="courseName">
              <el-input v-model="uploadForm.courseName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科任老师" prop="leaderName">
              <el-input v-model="uploadForm.leaderName" disabled   placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="考试" prop="examId">
              <el-select v-model="uploadForm.examId" placeholder="请选择" @change="handleExamPaperChange">
                <el-option
                    v-for="item in examOptions"
                    :key="item.examId"
                    :label="item.examCombinationName"
                    :value="item.examId"
                    :disabled="item.status == 0"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="试卷">
            <el-upload
                ref="uploadRef"
                v-model:file-list="fileList"
                action="javascript:void(0);"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :auto-upload="false"
                :on-change="onChange"
                accept="image/*"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" style="max-width: 100%; max-height: 100%" />
    </el-dialog>

    <!-- 学生导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的成绩数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
                type="primary"
                :underline="false"
                style="font-size: 12px; vertical-align: baseline"
                @click="importTemplate"
            >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Score">
import {ref, reactive, toRefs, getCurrentInstance, watch, nextTick} from "vue";
import * as echarts from 'echarts';
import * as clazzCourseApi from "@/api/school/clazzCourseApi";
import * as publicApi from "@/api/school/publicApi";
import * as scoreApi from "@/api/school/scoreApi";
import 'echarts-wordcloud';
import {getToken} from "@/utils/token";

/** 公共变量 */
const { proxy } = getCurrentInstance();
const { sys_status } = proxy.useDict('sys_status');
const gradeOptions = ref([]);
const clazzOptions = ref([]);
const courseOptions = ref([]);
const teacherOptions = ref([]);
const examOptions = ref([]);
const studentOptions = ref([]);
const knowledgeOptions = ref([]);

const clazzPhysicalScoreLineStats = ref(null);
const clazzPhysicalScoreLineStatsInstance = ref(null);

const clazzPhysicalScoreBarStats = ref(null);
const clazzPhysicalScoreBarStatsInstance =ref(null);

const clazzPhysicalScorePieStats = ref(null);
const clazzPhysicalScorePieStatsInstance = ref(null);

const clazzPhysicalScoreRectStats = ref(null);
const clazzPhysicalScoreRectStatsInstance =ref(null);

const clazzPhysicalScoreStackLineStats = ref(null);
const clazzPhysicalScoreStackLineStatsInstance = ref(null);

const clazzPhysicalScoreStackBarStats = ref(null);
const clazzPhysicalScoreStackBarStatsInstance =ref(null);

const clazzPhysicalScoreWordCloudStats = ref(null);
const clazzPhysicalScoreWordCloudStatsInstance = ref(null);

const tableData = ref([])

/** 年级列表 */
publicApi.allGradeList().then((response) => {
  gradeOptions.value = response
})
/** 课程列表 */
publicApi.allCourseList().then((response) => {
  courseOptions.value = response
})
/** 教师列表 */
publicApi.allTeacherList().then((response) => {
  teacherOptions.value = response
})

publicApi.allExamList().then((response) => {
  examOptions.value = response
})

const data = reactive({
  scoreQueryParams: {
    pageNum: 1,
    pageSize: 10,
    examId: undefined,
    courseId: undefined,
    clazzId: undefined,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    gradeId: undefined,
    clazzId: undefined,
    courseId: undefined,
    leaderId: undefined,
    status: undefined,
  },
  form: {
    examId:undefined,
    studentId:undefined,
    examScore:undefined,
    gradeId: undefined,
    clazzId: undefined,
    courseId: undefined,
    leaderId: undefined,
    status: 1,
    knowledgeIds: undefined,
    remark: undefined
  },
  batchForm: {
    examId:undefined,
    gradeId: undefined,
    clazzId: undefined,
    courseId: undefined,
    leaderId: undefined,
    status: 1,
    remark: undefined
  },
  uploadForm: {
    examId: undefined,
    clazzCourseId: undefined,
    paperPicture: undefined,
  },
  batchRules: {
    examId: [{ required: true, message: '考试不能为空', trigger: 'blur' }],
  },
  uploadRules: {
    examId: [{ required: true, message: '考试不能为空', trigger: 'blur' }],
  },
  rules: {
    examId: [{ required: true, message: '考试不能为空', trigger: 'blur' }],
    studentId: [{ required: true, message: '学生不能为空', trigger: 'blur' }],
    examScore: [{ required: true, message: '考试成绩不能为空', trigger: 'blur' }],
    // gradeId: [{ required: true, message: '年级不能为空', trigger: 'blur' }],
    // clazzId: [{ required: true, message: '班级不能为空', trigger: 'blur' }],
    // courseId: [{ required: true, message: '课程不能为空', trigger: 'blur' }],
    // leaderId: [{ required: true, message: '科任老师不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  }
})

const { queryParams, form, rules, scoreQueryParams, batchForm, uploadForm, batchRules, uploadRules } = toRefs(data)

/** 查询表单相关变量 */
const showSearch = ref(true);

/** 表格相关变量*/
const loading = ref(true);
const scoreLoading = ref(false);
const clazzCourseList = ref([]);
const scoreList = ref([]);
const total = ref(0);
const scoreTotal = ref(0);

/** 查询年级列表 */
function getList() {
  loading.value = true;
  clazzCourseApi
      .listClazzCourse(queryParams.value)
      .then((response) => {
        clazzCourseList.value = response.rows;
        total.value = response.total;
      })
      .finally(() => {
        loading.value = false;
      });
}
getList();

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 按钮操作区相关变量 */
const single = ref(true);
const multiple = ref(true);
const open = ref(false);
const title = ref('');
const ids = ref([]);

const batchTitle = ref('');
const batchOpen = ref(false)

const echartsTitle = ref('')
const echartsOpen = ref(false)

const uploadTitle = ref('')
const uploadOpen = ref(false)

/** 上传图片对话框相关变量 */
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileList = ref([])

function handleRemove(uploadFile, uploadFiles) {
  // console.log(uploadFile, uploadFiles)
  console.log(uploadFile)
  uploadForm.value.paperPicture = uploadFile.name
  proxy.$refs.uploadExamPaperRef.validate((valid) => {
    if (valid) {
      scoreApi.deleteExamPaper(uploadForm.value).then((response) => {
        proxy.$modal.msgSuccess('删除成功');
        handleExamPaperChange(uploadForm.value.examId)
      });
    }
  });
}

function onChange(uploadFile, uploadFiles) {
  // console.log(uploadFile, uploadFiles)
  // console.log(fileList.value)
  proxy.$refs.uploadExamPaperRef.validate((valid) => {
    if (valid) {
      const formData = new FormData();
      formData.append('file', uploadFile.raw);
      formData.append("examId", uploadForm.value.examId);
      formData.append("clazzCourseId", uploadForm.value.clazzCourseId);
      scoreApi.uploadExamPaper(formData).then((response) => {
        console.log(response)
        handleExamPaperChange(uploadForm.value.examId)
      })
    } else {
      proxy.$refs.uploadRef.clearFiles();
    }
  });
}

function handlePictureCardPreview(uploadFile) {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

/** 表单重置 */
function reset() {
  form.value = {
    clazzCourseId: undefined,
    examId: undefined,
    studentId: undefined,
    examScore: undefined,
    gradeId: undefined,
    clazzId: undefined,
    courseId: undefined,
    leaderId: undefined,
    status: 1,
    knowledgeIds: undefined,
    remark: undefined,
  };
  scoreList.value = []
  total.value = 0
  scoreQueryParams.value.examId= undefined;
  scoreQueryParams.value.studentId= undefined;
  knowledgeOptions.value = []
  proxy.resetForm('scoreRef');
}

function batchReset() {
  batchForm.value = {
    examId:undefined,
    gradeId: undefined,
    clazzId: undefined,
    courseId: undefined,
    leaderId: undefined,
    status: 1,
    remark: undefined
  }
  proxy.resetForm('batchScoreRef');
}

function uploadReset() {
  uploadForm.value = {
    examId: undefined,
    clazzCourseId: undefined,
    paperPicture: undefined,
  }

  proxy.resetForm('uploadExamPaperRef');
}

/** 新增按钮操作 */
// function handleAdd() {
//   reset();
//   open.value = true;
//   title.value = '添加班级课程';
// }

/** 修改按钮操作 */
function handleScoreEnter(row) {
  reset();
  const clazzCourseId = row.clazzCourseId || ids.value;
  clazzCourseApi.getClazzCourse(clazzCourseId).then((response) => {
    form.value = response;
    open.value = true;
    title.value = '成绩录入';
  });
  clazzChangeHandle(row.clazzId)
}

function handleScoreBatchEnter(row) {
  batchReset();
  const clazzCourseId = row.clazzCourseId || ids.value;
  clazzCourseApi.getClazzCourse(clazzCourseId).then((response) => {
    batchForm.value = response;
    batchOpen.value = true;
    batchTitle.value = '成绩批量录入';
  });
  clazzChangeHandle(row.clazzId)
}

function handleScoreEchartsView(row) {
  const clazzCourseId = row.clazzCourseId || ids.value;
  scoreApi.listEchartsData({clazzCourseId}).then((response) => {
    console.log(response)
    echartsOpen.value = true;
    echartsTitle.value = '成绩图表分析';
    nextTick(() => {
      lineChartBuild(response)
      barChartBuild(response)
      pieChartBuild(response)
      rectChartBuild(response)
      stackLineChartBuild(response)
      stackBarChartBuild(response)
      wordCloudChartBuild(response)
      tableData.value = response.tableData
    })

  })
}

function handleScoreUpload(row) {
  uploadReset();
  const clazzCourseId = row.clazzCourseId || ids.value;
  clazzCourseApi.getClazzCourse(clazzCourseId).then((response) => {
    fileList.value = []
    uploadForm.value = response;
    uploadForm.value.examId = undefined
    uploadForm.value.clazzCourseId = row.clazzCourseId
    uploadTitle.value = '上传试卷'
    uploadOpen.value = true
  });

}


/** 删除按钮操作 */
function handleScoreDelete(row) {
  const scoreIds = row.scoreId || ids.value;
  proxy.$modal
      .confirm(`是否确认删除成绩ID为"${scoreIds}"的数据项？`)
      .then(() => scoreApi.deleteScore(scoreIds))
      .then(() => {
        getScoreList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
      'school/clazz_course/export',
      {
        ...queryParams.value,
      },
      `clazz_course_${new Date().getTime()}.xlsx`,
  );
}


/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.clazzCourseId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs.scoreRef.validate((valid) => {
    if (valid) {
      scoreApi.addScore(form.value).then((response) => {
        proxy.$modal.msgSuccess('新增成功');
        open.value = false;
        getList();
      });
    }
  });
}

function submitBatchForm() {
  proxy.$refs.batchScoreRef.validate((valid) => {
    if (valid) {
      scoreApi.batchAddScore(batchForm.value).then((response) => {
        proxy.$modal.msgSuccess('批量新增成功');
        batchOpen.value = false;
        getList();
      });
    }
  });
}


/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

function cancelBatch() {
  batchOpen.value = false;
  batchReset();
}

watch(
    () => data.form.gradeId,
    (newValue, oldValue) => {
      console.log("newValue",newValue, "oldvalue", oldValue);
      if (newValue === undefined || newValue === null || newValue === "") {
        data.form.clazzId = undefined
      } else {
        publicApi.allClazzList({gradeId : newValue}).then((response) => {
          clazzOptions.value = response
        })
      }
    }
);

function gradeChangeHandle(gradeId) {
  console.log(gradeId)
  data.form.clazzId = undefined
}

watch(
    () => data.queryParams.gradeId,
    (newValue, oldValue) => {
      console.log("newValue",newValue, "oldvalue", oldValue);
      if (newValue === undefined || newValue === null || newValue === "") {
        data.queryParams.clazzId = undefined
      } else {
        publicApi.allClazzList({gradeId : newValue}).then((response) => {
          clazzOptions.value = response
        })
      }
    }
);

function queryGradeChangeHandle(gradeId) {
  console.log(gradeId)
  data.queryParams.clazzId = undefined
}

function clazzChangeHandle(clazzId) {
  publicApi.allStudentList({clazzId}).then((response) => {
    studentOptions.value = response
  })
}
/** 选择考试事件处理 */
function handleExamChange(examId) {
  if (examId === undefined || examId === null || examId === "") {
    return;
  }
  scoreQueryParams.value.examId= examId;
  scoreQueryParams.value.clazzId = form.value.clazzId
  scoreQueryParams.value.courseId = form.value.courseId
  getScoreList()

  publicApi.allKnowledgeList({examId}).then((response) => {
    knowledgeOptions.value = response;
  })
}

function handleExamPaperChange(examId) {
  scoreApi.listAllExamPaper({examId, clazzCourseId: uploadForm.value.clazzCourseId}).then((response) => {
    console.log(response)
    fileList.value = []
    response.forEach((item, i) => {
       fileList.value.push({
         name: item.paperPicture,
         url: import.meta.env.VITE_APP_BASE_API + item.paperPicture
       })
    });
  })
}

/** 选择学生事件处理 */
function handleStudentChange(studentId) {
  if (studentId === undefined || studentId === null || studentId === "") {
    return;
  }
  scoreQueryParams.value.studentId= studentId;
  scoreQueryParams.value.clazzId = form.value.clazzId
  scoreQueryParams.value.courseId = form.value.courseId
  if (scoreQueryParams.value.examId === undefined || scoreQueryParams.value.examId === null || scoreQueryParams.value.examId === "") {
    return;
  }
  getScoreList()
}

function getScoreList() {
  scoreLoading.value = true;
  form.value.examScore = undefined;
  scoreApi
      .listScore(scoreQueryParams.value)
      .then((response) => {
        scoreList.value = response.rows;
        scoreTotal.value = response.total;
        Object.keys(scoreList.value).map(key => {
          let score = scoreList.value[key];
          if (score.studentId === form.value.studentId) {
            form.value.examScore = score.examScore
            form.value.remark = score.remark
            form.value.knowledgeIds = score.knowledgeIds
          }
        })
      })
      .finally(() => {
        scoreLoading.value = false;
      });
}

function handleExamBatchChange(examId) {
  if (examId === undefined || examId === null || examId === "") {
    return;
  }
  Object.keys(studentOptions.value).map(key => {
    batchForm.value['examScore_' + studentOptions.value[key].studentId] = undefined
  })

  scoreApi.listAllScore({
   examId,
   ...batchForm.value
  }).then((response) => {
    // console.log(response)
    Object.keys(response).map(key => {
      let score = response[key];
      batchForm.value['examScore_'+score.studentId] = score.examScore
    })
  })
}

//构造折线图
function lineChartBuild(response) {
  const clazzPhysicalScoreStatsInstance = echarts.init(clazzPhysicalScoreLineStats.value, 'macarons');
  let option = {
    legend: {},
    tooltip: {},
    dataset: {
      source: response.objListList
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        interval: 0,
        formatter: function (value) {
          return value.split('').join('\n')
        }
      }
    },
    yAxis: {},
    // Declare several bar series, each will be mapped
    // to a column of dataset.source by default.
    series: response.seriesLineList
  }
  clazzPhysicalScoreStatsInstance.setOption(option);
  clazzPhysicalScoreLineStatsInstance.value = clazzPhysicalScoreStatsInstance
}

//构造柱状图
function barChartBuild(response) {
  const clazzPhysicalScoreStatsInstance = echarts.init(clazzPhysicalScoreBarStats.value, 'macarons');
  let option = {
    legend: {},
    tooltip: {},
    dataset: {
      source: response.objListList
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        interval: 0,
        formatter: function (value) {
          return value.split('').join('\n')
        }
      }
    },
    yAxis: {},
    // Declare several bar series, each will be mapped
    // to a column of dataset.source by default.
    series: response.seriesBarList
  }
  clazzPhysicalScoreStatsInstance.setOption(option);
  clazzPhysicalScoreBarStatsInstance.value = clazzPhysicalScoreStatsInstance
}


//构造饼图
function pieChartBuild( response) {
  const clazzPhysicalScoreStatsInstance = echarts.init(clazzPhysicalScorePieStats.value, 'macarons');
  let option = {
    title: {
      text: '课程成绩等级分布饼图',
      // subtext: '分数划分区域',
      left: 'center'
      // bottom: '5%'
    },
    tooltip: {
      trigger: 'item'
    },
    toolbox: {
      show: true,
      right: 20,
      top: 10,
      feature: {
        saveAsImage: {}
      }
    },
    legend: {
      bottom: '5%',
      left: 'center'
    },
    series: [
      {
        name: '分数区间',
        type: 'pie',
        radius: '50%',
        data:  response.pieDataList,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        itemStyle: {
          normal: {
            label: {
              show: true,
              formatter: '{b} : {c} ({d}%)'
            },
            labelLine: {
              show: true
            }
          }
        }
      }
    ]
  }
  clazzPhysicalScoreStatsInstance.setOption(option);
  clazzPhysicalScorePieStatsInstance.value = clazzPhysicalScoreStatsInstance
}


//构造直方图
function rectChartBuild(response) {
  const clazzPhysicalScoreStatsInstance = echarts.init(clazzPhysicalScoreRectStats.value, 'macarons');

  let mylinedata = []
  for (let i = 0; i < response.histogramData.length; i++) {
    mylinedata.push(response.histogramData[i][2])
  }
  let mydata = response.histogramData.map(function (item, index) {
    return {
      value: item,
      itemStyle: {
        // color: '#9bbb59'
      }
    }
  })

  function renderItem (params, api) {
    let yValue = api.value(2)
    let start = api.coord([api.value(0), yValue])
    let size = api.size([api.value(1) - api.value(0), yValue])
    let style = api.style()

    return {
      type: 'rect',
      shape: {
        x: start[0],
        y: start[1],
        width: size[0],
        height: size[1]
      },
      style: style
    }
  }

  let option = {
    title: {
      text: '课程成绩得分统计直方图',
      left: 'center'
    },
    tooltip: {},
    xAxis: [{
      scale: true,
      type: 'value',
      min: 0,
      max: response.fullScore,
      interval: 10
    }, {
      type: 'category',
      show: false,
      data: response.lineTitleArray
    }],
    yAxis: {},
    series: [{
      type: 'custom',
      renderItem: renderItem,
      label: {
        show: true,
        position: 'top'
      },
      dimensions: ['from', 'to', '人数'],
      encode: {
        x: [0, 1],
        y: 2,
        tooltip: [0, 1, 2],
        itemName: 3
      },
      data: mydata
    }, {
      type: 'line',
      smooth: true,
      xAxisIndex: 1,
      itemStyle: {
        normal: {
          color: '#275F82', // 改变折线点的颜色
          lineStyle: {
            color: '#253A5D' // 改变折线颜色
          }
        }
      },
      data: mylinedata
    }]
  }
  clazzPhysicalScoreStatsInstance.setOption(option);
  clazzPhysicalScoreRectStatsInstance.value = clazzPhysicalScoreStatsInstance
}

function stackLineChartBuild(response) {
  const clazzPhysicalScoreStatsInstance = echarts.init(clazzPhysicalScoreStackLineStats.value, 'macarons');
  let objData = response.objListList;
  let title = []
  for (let i = 0; i < objData.length-1; i++) {
    title.push(objData[i+1][0])
  }
  let legendData = []
  for (let j = 0; j < objData[0].length - 1; j++) {
    legendData.push(objData[0][j+1])
  }
  let seriesData = []
  for (let i = 0; i < objData[0].length-1; i++) {
    let obj = {
      name: objData[0][i+1],
      type: 'line',
      stack: 'total',
      label: {
        show: true,
        position: 'top'
      },
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: []
    }
    for (let j = 0; j < objData.length - 1; j++) {
      obj.data.push(objData[j + 1][i + 1])
    }
    seriesData.push(obj)
  }

  let option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: legendData
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    yAxis: {
      type: 'value'
    },
    xAxis: {
      type: 'category',
      data: title,
      boundaryGap: false,
      axisLabel: {
        interval: 0,
        formatter: function (value) {
          return value.split('').join('\n')
        }
      }
    },
    series: seriesData
  }
  clazzPhysicalScoreStatsInstance.setOption(option);
  clazzPhysicalScoreStackLineStatsInstance.value = clazzPhysicalScoreStatsInstance
}

function stackBarChartBuild(response) {
  const clazzPhysicalScoreStatsInstance = echarts.init(clazzPhysicalScoreStackBarStats.value, 'macarons');
  let objData = response.objListList;
  let title = []
  for (let i = 0; i < objData.length-1; i++) {
    title.push(objData[i+1][0])
  }
  let legendData = []
  for (let j = 0; j < objData[0].length - 1; j++) {
    legendData.push(objData[0][j+1])
  }
  let seriesData = []
  for (let i = 0; i < objData[0].length-1; i++) {
    let obj = {
      name:  objData[0][i+1],
      type: 'bar',
      stack: 'total',
      label: {
        show: true
      },
      emphasis: {
        focus: 'series'
      },
      data: []
    }
    for (let j = 0; j < objData.length - 1; j++) {
      obj.data.push(objData[j + 1][i + 1])
    }
    seriesData.push(obj)
  }

  let option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: legendData
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    yAxis: {
      type: 'value'
    },
    xAxis: {
      type: 'category',
      data: title,
      axisLabel: {
        interval: 0,
        formatter: function (value) {
          return value.split('').join('\n')
        }
      }
    },
    series: seriesData
  }
  clazzPhysicalScoreStatsInstance.setOption(option);
  clazzPhysicalScoreStackBarStatsInstance.value = clazzPhysicalScoreStatsInstance

}

function wordCloudChartBuild(response) {
  const clazzPhysicalScoreStatsInstance = echarts.init(document.getElementById('clazzPhysicalScoreStats'), 'macarons');
  let option = {
    tooltip: {
      show: true
    },
    series: [
      {
        type: 'wordCloud',
        data: response.wordDataList,
        textStyle: {
          fontFamily: 'sans-serif',
          fontWeight: 'bold',
          // Color can be a callback function or a color string
          color: function () {
            // Random color
            return 'rgb(' + [
              Math.round(Math.random() * 160),
              Math.round(Math.random() * 160),
              Math.round(Math.random() * 160)
            ].join(',') + ')';
          }
        },
        emphasis: {
          focus: 'self',

          textStyle: {
            textShadowBlur: 10,
            textShadowColor: '#333'
          }
        },
        //shape: 'circle', // 词云图显示排列为什么形状，默认 circle，cardioid 心形，diamond 菱形
        // textStyle: {
        //   normal: {
        //     fontFamily: 'sans-serif',
        //     fontWeight: 'bold',
        //     color: function () {
        //       // 随即配色，每次刷新页面都会显示不同颜色
        //       return (
        //           'rgb(' +
        //           [
        //             Math.round(Math.random() * 160),
        //             Math.round(Math.random() * 160),
        //             Math.round(Math.random() * 160)
        //           ].join(',') +
        //           ')'
        //       )
        //     }
        //   }
        // },
        // emphasis: {
        //   focus: 'self',
        //   textStyle: {
        //     textShadowBlur: 10,
        //     textShadowColor: '#333'
        //   }
        // }
      }
    ]
  };
  clazzPhysicalScoreStatsInstance.setOption(option);
  clazzPhysicalScoreWordCloudStatsInstance.value = clazzPhysicalScoreStatsInstance
}



/** * 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: `Bearer ${getToken()}` },
  // 上传的地址
  url: `${import.meta.env.VITE_APP_BASE_API}/school/score/importData`,
});

/** 导入按钮操作 */
function handleImport() {
  upload.title = '成绩批量导入';
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('school/score/importTemplate', {}, `score_template_${new Date().getTime()}.xlsx`);
}
/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs.uploadRef.clearFiles();
  proxy.$alert(
      `<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>${response.msg}</div>`,
      '导入结果',
      { dangerouslyUseHTMLString: true },
  );
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs.uploadRef.submit();
}

</script>

<style scoped>
.el-select {
  width: 180px;
}

</style>

<style>
.el-form-item__label {
  font-weight: 700;
}
</style>
